package com.asialjim.wechat.spring.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Objects;

/**
 * <h1><em>ASIAL JIM JAVA DOC</em></h1><hr/>
 * <h2>CLASS DESCRIPTION <i>[ NAME: WeChatHttpHelper ]</i></h2><strong>
 * <p> we chat helper
 * </strong><p><p><em>Copyright &copy; Asial Jim Co., LTD</em><hr/>
 *
 * @author Asial Jim &nbsp;&nbsp; <span>Email:<a href="mailto:asialjim@hotmail.com">asialjim@hotmail.com</a> &nbsp;&nbsp; <a href="asialjim@qq.com">asialjim@qq.com</a></span>
 * @version 1.0.0
 * @since 2021/3/16   &nbsp;&nbsp; JDK 8
 */
public class WeChatHttpHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(WeChatHttpHelper.class);

    public static String bodyString(ServletRequest req){
        StringBuilder sb = new StringBuilder();
        InputStream is = null;
        BufferedReader reader = null;
        try {
            is = req.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8".intern())));
            String line = "";
            while ((line = reader.readLine()) != null){
                sb.append(line);
            }
        } catch (IOException e) {
            LOGGER.error("wrap http request body string error:[{}]",e.getMessage(),e);
        } finally {
            try {
                if (Objects.nonNull(is)) {
                    is.close();
                }
                if (Objects.nonNull(reader)){
                    reader.close();
                }
            } catch (IOException e) {
                LOGGER.error("close I/O error:[{}]",e.getMessage(),e);
            }
        }
        return sb.toString();
    }
}
